import React, { useState, useEffect, useRef } from 'react';

const LazyLoadList = () => {
    const [list, setList] = useState([]); // 列表数据
    const [isLoading, setIsLoading] = useState(false); // 是否正在加载
    const pageRef = useRef(1); // 当前页数
    const listRef = useRef(null); // 列表的ref
    console.log('listRef',listRef)
    useEffect(() => {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach((entry) => {
                if (entry.isIntersecting && !isLoading) {
                    // 当列表最后一个元素进入视口并且没有正在加载时，加载更多数据
                    setIsLoading(true);
                    loadMoreData();
                }
            });
        });

        if (listRef.current) {
            observer.observe(listRef.current);
        }

        console.log('222',222)
        return () => {
            console.log('111',111)
            if (listRef.current) {
                observer.unobserve(listRef.current);
            }
        };
    }, [list, isLoading]);

    // 模拟加载更多数据的函数
    const loadMoreData = () => {
        // 模拟API请求
        setTimeout(() => {
            const newData = [...list];
            for (let i = 0; i < 10; i++) {
                newData.push(`Item ${pageRef.current * 10 + i}`);
            }
            setList(newData);
            pageRef.current++;
            setIsLoading(false);
        }, 1000);
    };

    return (
        <ul>
            <button onClick={() => { loadMoreData() }}>加载更多</button>
            {list.map((item, index) => {
                if (index === list.length - 1) {
                    return (
                        // listRef 存储最后一个li dom对象
                        <li key={index} ref={listRef}>
                            {item}
                        </li>
                    );
                } else {
                    return <li key={index}>{item}</li>;
                }
            })}
            {isLoading && <li>Loading...</li>}
        </ul>
    );
};

export default LazyLoadList;